package com.free4inno.knowledgems.interceptor;

import com.free4inno.knowledgems.openapi.OpenAPIException;
import com.free4inno.knowledgems.openapi.ResultEnum;
import com.free4inno.knowledgems.service.AppKeyService;
import com.free4inno.knowledgems.utils.LogUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author HUYUZHU.
 * Date 2021/10/24 17:32.
 */

@Slf4j
@Component
public class OpenAPIInterceptor implements HandlerInterceptor {

    @Autowired
    private AppKeyService appKeyService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String appkey = httpServletRequest.getParameter("appkey");
        if ((Boolean) appKeyService.checkAppKey(appkey).get("result")) {
            log.info(LogUtils.parse("openapi鉴权", "鉴权通过,appkey:" + appkey));
            return true;
        } else {
            log.error(LogUtils.parse("openapi鉴权", "鉴权通过,appkey:" + appkey));
            throw new OpenAPIException(ResultEnum.ACCESS_ERROR);
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }

}
